package com.cyj.dream.core.util.file;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description: 阿里easyExcel工具类
 * @BelongsProject: fckj-restaurant
 * @BelongsPackage: com.fckj.fckjrestaurant.util.file
 * @Author: ChenYongJia
 * @CreateTime: 2021-4-1 09:31:22
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
public class EasyExcelUtils {

    /**
     * 使用阿里的 easyExcel-2.2.6 处理报表导出
     *
     * @param response 相应的 Controller 方法返回值需要返回空======>void
     * @param listData 查询所得的数据
     * @param fileName 导出报表的名字
     * @param clazz    数据对应实体（需要使用 easyExcel 注解：@ExcelProperty(value = "性别", index = 0,converter = SexConverter.class)）
     */
    public static void exportExcle(HttpServletResponse response, List listData, String fileName, Class clazz) {
        // 达到10W条一个工作表
        Integer counts = 100000;
        try {
            // 设置响应格式
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String name = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + name + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            // response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + name + ".xlsx");

            // 获取输出流
            ServletOutputStream outputStream = response.getOutputStream();

            // 获取工作簿对象
            ExcelWriter excelWriter = EasyExcel.write(outputStream, clazz).build();

            // 获取工作表数量
            Integer sheetNum = 1;
            if (listData.size() < counts) {
                sheetNum = 1;
            } else {
                // 这里我是根据自身工作需要设置每 counts 条数据一个 sheet
                sheetNum = listData.size() % counts == 0 ? listData.size() / counts : listData.size() / counts + 1;
            }

            // 去调用写入,这里我调用了 sheetNum 次，实际使用时根据数据库分页的总的页数来。这里最终会写到 sheetNum 个 sheet 里面
            List<T> subList = null;
            for (int i = 0; i < sheetNum; i++) {
                // 每次都要创建 writeSheet 这里注意必须指定 sheetNo
                WriteSheet writeSheet = EasyExcel.writerSheet(i, fileName + i).build();
                // 这里是将查询的数据分为若干个 sheet 页
                subList = listData.subList(i * counts, i == sheetNum - 1 ? listData.size() : (i + 1) * counts);
                excelWriter.write(subList, writeSheet);
            }

            // finish 会帮忙关闭流
            excelWriter.finish();
        } catch (IOException e) {
            log.error("导出excel时IOE异常，异常为===>" + e);
        }
    }

}
